import { Component, OnInit } from '@angular/core';
import { ApiService } from '@core/api.service';
import { _HttpClient } from '@delon/theme';
import { DatePipe } from '@angular/common';
import { LocalStorage } from '@core/local.storage';
import { environment } from '../../../../environments/environment';
import { ZhpdService } from './zhpd.service';
import { StationDevtypeService } from '@core/stationDevtype.service';
import { TreeTools } from '@core/treeTools.tool';
import { ControlApiService } from '@core/controlApi.service';
import { StatusFollowService } from '@core/statusFollow.service';

@Component({
  selector: 'app-zhpd',
  templateUrl: './zhpd.component.html',
  styleUrls: ['./zhpd.less']
})
export class ZhpdComponent implements OnInit {

  userInfo = JSON.parse(this.ls.get('loginInfo'));
  queryParam: any = {};
  cjList: any[] = [];
  gqList: any[] = [];
  czList: any[] = [];
  treeNodeStyle = { 'max-width': '300px', 'max-height': '400px', 'overflow-y': 'auto', 'overflow-x': 'hidden' };
  titleDate = new Date();
  // expandGrid: any[] = [];
  lockHeadScroll = { x: '1600px', y: `80vh` };
  lockHeadScroll2 = { x: '1000px', y: `500px`, };
  detail: any = {
    tableData: [],
    visible: false,
    selectedValue: '20',
    pageIndex: 1,
    pageTotal: 0,
    footer: [{
      _this: this,
      label: '关闭', // 按钮文本
      onClick() {
        this._this.detailCancel();
      }
    }],
    detailCancel() {
      this.visible = false;
    },
    selectedChange: (v) => {
      // this.lastDetailParam.limit = v;
      this.queryDetail(this.lastDetailParam);
    },
    pageIndexChange: (v) => {
      // this.lastDetailParam.page = v;``
      this.queryDetail(this.lastDetailParam);
    },
    tableDbclick: (row) => {

      const param = {
        NID: row.N_ID, //  报警ID
        STATIONID: row.STATIONID, //  车站ID
        STATIONNAME: row.STATIONNAME, //  车站中文名，用encodeURI(encodeURI())包两层
        ALARMLEVEL: row.ALARMLEVEL, //  报警等级
        ALARMTEXT: row.ALARMTEXT, //  报警名称
        ALARMTYPE: row.ALARMTYPE, //  报警类型ID
        DEVTYPEID: row.DEV_TYPE, //  设备类型ID
        DEVTYPE: row.DEVTYPENAME, //  设备类型中文名，用encodeURI(encodeURI())包两层
        DEVNAME: row.DEVNAME, //  设备中文名，用encodeURI(encodeURI())包两层
        TIME: this.datePipe.transform(row.U_TIME, 'yyyy-MM-dd HH:mm:ss'), //  报警时间 格式：2019-11-13 10:24:34
        ALARMDESCRIPTION: row.ALARMDESCRIPTION, //  处置流程，可为空
      };
      const url = environment.outLink + '/#/control/diagnose?' + this.zhpdService.parseParams(param).toString();
 
      window.open(url);
    }
  };
  main: any = {
    tableData: [],
    selectedValue: '20',
    pageIndex: 1,
    pageTotal: 0,
    selectedChange: () => {
      this.query();
    },
    pageIndexChange: (v) => {
      this.query(v, this.main.selectedValue);
    },
    tableDbclick: (row) => {
      this.detail.visible = true;
      this.detail.tableData = [];
      const utime = this.datePipe.transform(this.queryParam._scoredate, 'yyyy-MM-dd');
      const param = {
        utime,
        stationid: row.stationid,
        devtypeid: row.devtypeid,
        dev: row.dev,
      };
      this.lastDetailParam = param;
      this.queryDetail(param);
    }
  };
  devTypeSelect: any[] = [];
  devTypeId: string;
  devNodes: any[] = [];
  lastDetailParam: any = {};


  constructor(
    private apiService: ApiService,
    private datePipe: DatePipe,
    public ls: LocalStorage,
    private zhpdService: ZhpdService,
    private controlApiService: ControlApiService,
    private treeTools: TreeTools,
    private statusFollowService: StatusFollowService,
    private statdevtype: StationDevtypeService
  ) {  }

  test() {
    this.detail.tableDbclick();
  }

  ngOnInit(): void {
    this.initCmp();
    this.query();
  }

  initCmp() {
    this.getCj();
    this.initDate();
    // this.getGq();
    // this.getCz();
  }

  initDate() {
    const _date = new Date();
    _date.setDate(_date.getDate() - 1);
    this.queryParam._scoredate = _date;
  }

  statusFollow(data) {
    return this.statusFollowService.init('8', data);
  }

  /**
   * 删除私立字段
   * @param param
   */
  removePrivateFields(param) {
    Object.keys(param).forEach(key => {
      if (key.indexOf('_') == 0) {
        delete param[key];
      }
    });
  }

  formatDate(param) {
    if (param._scoredate) {
      param.scoredate =this.datePipe.transform(param._scoredate, 'yyyy-MM-dd');
    }
  }

  /**
   * 删除null字段
   * @param param
   */
  removeUselessFields(param) {
    Object.keys(param).forEach(key => {
      if (!param[key]) {
        delete param[key];
      }
    });
  }

  transDevType(param, func) {
    let devtypeName = '';
    if (param.devtypeid) {
      devtypeName = this.treeTools.getTreeNodeName({
        id: param.devtypeid,
        nodes: this.devTypeSelect
      });

      const _param = {
        lxid: this.queryParam.devtypeid,
        lx: devtypeName,
        types: '1',
      };
      this.zhpdService.tranDev(_param);
    } else if (param.dev) {
      const _param = {
        lxid: this.queryParam.devtypeid,
        lx: devtypeName,
        types: '1',
        mcid: param.dev,
        mc: '',
      };
      this.zhpdService.tranDev(_param);
    } else {
      func();
    }

  }

  query(pageIndex?, rows?) {
    const param: any = {
      page: pageIndex || this.main.pageIndex,
      limit: rows || this.main.selectedValue,
    };
    Object.assign(param, this.queryParam);
    this.formatDate(param);
    this.removePrivateFields(param);
    this.removeUselessFields(param);
    this.zhpdService.query(param).subscribe(res => {
      this.main.tableData = res.data;
      this.main.pageTotal = res.count;
    });
    // this.transDevType(param, (devTypeId) => {
    //   if (devTypeId) {
    //     param.devtypeid = devTypeId;
    //   }

    // });
  }

  queryDetail(_param) {
    const param = {
      page: this.detail.pageIndex,
      limit: this.detail.selectedValue,
    };
    Object.assign(param, _param);
    this.removeUselessFields(param);
    this.zhpdService.alarmTabQuery(param).subscribe(res => { 
      this.detail.tableData = res.data;
      this.detail.pageTotal = res.count;
    });
  }



  getCj() {
    this.apiService.getAllChejian('1').subscribe(res => {
      this.cjList = res;
    });
  }
  onChangeCj(v) {
    this.getGq(v);
  }

  getGq(cjId) {
    if (!cjId) {
      return;
    }
    this.apiService.getgongquByCjId(cjId).subscribe(res => {
      this.gqList = res;
    });
  }
  onChangeGq(v) {
    this.getCz(v);
  }

  getCz(gqId) {
    if (!gqId) {
      return;
    }
    this.apiService.getStationByOrgId(gqId, '1').subscribe(res => {
      this.czList = res;
    });
  }
  onChangeCz(czId) {
    if (!czId) {
      return;
    }
    this.getAllTypesByStaId(czId);
  }

  // 设备类型
  getAllTypesByStaId(stationId) {
    if (!stationId) {
      return;
    }
    // this.devTypeIf = false;
    this.devTypeSelect = [];
    this.devTypeId = '';

    this.statdevtype.getDevType(stationId, (resdata) => {
      this.treeTools.formatTreeNodes({
        nodes: resdata,
        selectOnlyLeaf: true,
      });
      this.devTypeSelect = resdata;
      // this.getjcbjtype(this.devTypeId);
      // this.getAllDevName();
    });
  }

  devTypeChange(v) {
    if (!v) {
      return;
    }
    this.getAllDevName(v);
  }


  // 报警设备
  getAllDevName(devTypeId) {
    const stationId = this.queryParam.stationid;
    if (stationId && devTypeId) {
      this.devNodes = [];
      this.controlApiService.getDevByStationType(stationId, devTypeId).subscribe(res => {
        if (res.type === 'success') {
          const data = res.response.data;
          this.devNodes = data;
          // this.devNameId = this.devNodes[0].id;
          // this.devNameText = this.devNodes[0].name;
        }
      });
    }
  }
}
